package com.lizardtech.djvu.codecs
{
	import com.lizardtech.djvu.IFFChunk;
	import com.lizardtech.djvu.djCodec;
	
	public class djINFO extends djCodec
	{
	  /** The gamma correction factor. */
	  public var gamma:Number= 2.2;
	
	  /** The scanned resolution. */
	  public var dpi:int= 300;
	
	  /** Flags with addition details. */
	  public var flags:int= 0;
	
	  /** The height of the page in pixels at scanned resolution. */
	  public var height:int= 0;
	
	  /** The version of the format specification this page complies with. */
	  public var version:int= 20;
	
	  /** The width of the page in pixels at scanned resolution. */
	  public var width:int= 0;
		
		public function djINFO() {
			super();
		}

		public override function decode(chunk:IFFChunk):void { 
		    var buffer: Array= chunk.toIntArray();
		    var size:int = buffer.length;
		
		    if(size < 5)
		    {
		      throw new Error(
		        "DjVuInfo: Corrupted file (truncated INFO chunk)");
		    }
		
		    width     = ((0xff & buffer[0]) << 8) | (0xff & buffer[1]);  //0x&
		    height    = ((0xff & buffer[2]) << 8) | (0xff & buffer[3]);
		    version   = 0 & buffer[4];
		
		    if((size >= 6) && (buffer[5] != -1))
		    {
		      version = ((0xff & buffer[5]) << 8) | version;
		    }
		
		    if((size >= 8) && (buffer[7] != -1))
		    {
		      dpi = ((0xff & buffer[7]) << 8) | (0xff & buffer[6]);
		
		      if((dpi < 25) || (dpi > 6000))
		      {
		        dpi = 300;
		      }
		    }
		
		    if(size >= 9)
		    {
		      if((buffer[8] >= 3) || (buffer[8] <= 50))
		      {
		        gamma = 0.1* buffer[8];
		      }
		    }
		
		    if(size >= 10)
		    {
		      flags = buffer[9];
		    }
		
		    if((width < 0) || (height < 0))
		    {
		      throw new Error(
		        "DjVu Decoder: Corrupted file (image size is zero)");
		    }
		    trace("decoded: djINFO: " + height + "x" + width +" @ " + dpi + "dpi");
	   }
		
	}
}